# _*_ coding:utf-8 _*_
# @Time  : 2023.05.13
# @Author: zizlee

from fastapi import APIRouter, Body, Query
from pydantic import BaseModel, constr, conint, validator
from db_utils import BaseDatabaseConnection
from response import APIResponse
from constant import VarietyConstants


class VarietyItem(BaseModel):
    name: constr(min_length=1, max_length=32)
    code: constr(min_length=1, max_length=32)
    group_id: int
    price_unit: str
    scope: str
    is_exchange: conint(ge=0, le=1)

    @validator('scope')
    def validate_scope(cls, value):
        v_scope = []
        for s in value.split(','):
            if s in VarietyConstants.SCOPES:
                v_scope.append(s)
        if len(v_scope) < 1:
            raise ValueError('variety scope error!')
        v_scope.sort()
        return ','.join(v_scope)

    @validator('group_id')
    def validate_group_id(cls, value):
        if value not in VarietyConstants.GROUPS:
            raise ValueError('variety group error!')
        return value


class CreateVarietyItem(VarietyItem):
    pass


class UpdateVarietyItem(VarietyItem):
    vid: int  # 修改的条目id
    sort_num: int
    is_active: bool


class Variety:
    def __init__(self, code: str = None, scope: str = None, keyword: str = None):
        self.code = code
        self.scope = scope
        self.keyword = keyword

    def create_variety(self, v_item: CreateVarietyItem):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
                INSERT INTO ruizhi_variety (name,code,group_id,price_unit,scope,is_exchange,is_active)
                VALUES (%s,%s,%s,%s,%s,%s,%s);
            """, [v_item.name, v_item.code, v_item.group_id, v_item.price_unit, v_item.scope, v_item.is_exchange, 0])
        return APIResponse.success(msg='创建品种成功!')

    def retrieve_variety(self):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
                SELECT id,create_time,name,code,group_id,price_unit,scope,sort_num,is_exchange,is_active
                FROM ruizhi_variety ORDER BY is_exchange DESC,sort_num;
            """)
            v_list = list(conn.cursor.fetchall())
        if self.scope:
            v_list = list(filter(lambda x: self.scope in x['scope'].split(','), v_list))
        if self.code:
            v_list = list(filter(lambda x: self.code == x['code'], v_list))
        if self.keyword:
            v_list = list(filter(lambda x: self.keyword in x['code'] or self.keyword in x['name'], v_list))

        for v in v_list:
            scope_list = v['scope'].split(',')
            scope_list.sort()
            v['group_name'] = VarietyConstants.group_name(v['group_id'])
            v['scope_names'] = [VarietyConstants.scope_name(s) for s in scope_list]
        return APIResponse.success(data={'data': v_list})

    def update_variety(self, v_item: UpdateVarietyItem):
        sql = """
            UPDATE ruizhi_variety SET name=%s,group_id=%s,price_unit=%s,scope=%s,sort_num=%s,is_exchange=%s,is_active=%s
            WHERE code=%s LIMIT 1;
        """
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute(sql, [v_item.name, v_item.group_id, v_item.price_unit, v_item.scope, v_item.sort_num,
                                      v_item.is_exchange, v_item.is_active, self.code])
        return APIResponse.success(msg='修改指标信息成功!')


variety_api = APIRouter()


@variety_api.get('/scopes/')  # 获取品种的使用范围
def get_variety_scopes():
    return APIResponse.success(data=[{'key': k, 'name': v} for k, v in VarietyConstants.SCOPES.items()])


@variety_api.post('/create/')
def create_variety(v_item: CreateVarietyItem = Body(...)):
    return Variety().create_variety(v_item=v_item)


@variety_api.get('/retrieve/')
def retrieve_variety(code: str = Query(''), scope: str = Query(''), kw: str = Query(''), ):
    return Variety(code=code, scope=scope, keyword=kw).retrieve_variety()


@variety_api.put('/update/')
def update_variety(v_item: UpdateVarietyItem = Body(...)):
    return Variety(code=v_item.code).update_variety(v_item=v_item)
